<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>关键词 → 问题生成 → 模型选择 · Demo</title>
  <!-- Tailwind Play CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
   <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            brand: '#2563eb',     // 主色（蓝）
            subtle: '#f1f5f9',    // 淡灰卡片底
            line: '#e5e7eb',      // 分隔线
            soft: '#f8fafc'
          },
          boxShadow: {
            card: '0 10px 30px rgba(15, 23, 42, .06)'
          }
        }
      }
    }
  </script>
  <style>

    .prose {
  color: #334155;
}

.prose :where(p):not(:where([class~="not-prose"] *)) {
  margin-top: 0;
  margin-bottom: 1rem;
  line-height: 1.75;
}

.prose :where(strong):not(:where([class~="not-prose"] *)) {
  color: #1e293b;
  font-weight: 600;
}

.prose :where(ul):not(:where([class~="not-prose"] *)) {
  margin-top: 0;
  margin-bottom: 1rem;
  padding-left: 1.5rem;
}

.prose :where(ol):not(:where([class~="not-prose"] *)) {
  margin-top: 0;
  margin-bottom: 1rem;
  padding-left: 1.5rem;
}

.prose :where(li):not(:where([class~="not-prose"] *)) {
  margin-bottom: 0.25rem;
}

.prose :where(a):not(:where([class~="not-prose"] *)) {
  color: #2563eb;
  text-decoration: underline;
}

.prose :where(a):not(:where([class~="not-prose"] *)):hover {
  color: #1d4ed8;
}

.prose :where(h1):not(:where([class~="not-prose"] *)) {
  font-size: 1.5rem;
  margin-top: 0;
  margin-bottom: 1rem;
  font-weight: 600;
}

.prose :where(h2):not(:where([class~="not-prose"] *)) {
  font-size: 1.25rem;
  margin-top: 0;
  margin-bottom: 0.75rem;
  font-weight: 600;
}

.prose :where(h3):not(:where([class~="not-prose"] *)) {
  font-size: 1.125rem;
  margin-top: 0;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.prose :where(hr):not(:where([class~="not-prose"] *)) {
  margin-top: 1.5rem;
  margin-bottom: 1.5rem;
  border: 0;
  border-top: 1px solid #cbd5e1;
}

.prose :where(blockquote):not(:where([class~="not-prose"] *)) {
  margin-top: 0;
  margin-bottom: 1rem;
  padding-left: 1rem;
  border-left: 3px solid #cbd5e1;
  color: #64748b;
}

.prose :where(code):not(:where([class~="not-prose"] *)) {
  background-color: #f1f5f9;
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.875em;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}

    /* 打印优化：展开所有 details，隐藏交互按钮，仅保留核心内容 */
    @media print {
      header, .no-print { display:none !important; }
      details { page-break-inside: avoid; }
      details[open] > summary { border-bottom: 1px solid #e5e7eb; margin-bottom: .5rem; }
      /* 让图片填满宽度，避免分页截断 */
      img { max-width: 100% !important; page-break-inside: avoid; }
      .page { box-shadow: none !important; border: none !important; }
    }
    /* 小增强：details 的箭头视觉 */
    summary::-webkit-details-marker{display:none}
    summary .caret::after{content:'▸'; display:inline-block; transition:.2s; margin-right:.5rem}
    details[open] summary .caret::after{transform:rotate(90deg)}
  </style>
</head>

<body class="bg-slate-50 text-slate-900">
  <!-- ========== 顶部栏 / 步骤指示 ========== -->
  <header class="sticky top-0 z-20 bg-white/90 backdrop-blur">
    <div class="mx-auto max-w-6xl px-6">
      <div class="flex items-center justify-between py-4">
        <div class="flex items-center gap-3">
          <div class="h-9 w-9 rounded-xl bg-brand/10 text-brand grid place-content-center text-lg font-semibold">G</div>
          <div class="text-sm">
            <div class="font-semibold leading-4">GEO Studio</div>
            <div class="text-slate-500 leading-4">关键词 → 问题生成 → 模型选择</div>
          </div>
        </div>

        <!-- 步骤条 -->
        <ol class="flex items-center gap-3 text-sm">
          <li class="flex items-center gap-2">
            <span class="h-6 w-6 rounded-full bg-brand text-white grid place-content-center">1</span>
            <span class="hidden sm:inline">生成问题</span>
          </li>
          <span class="h-px w-10 bg-line"></span>
          <li class="flex items-center gap-2">
            <span id="step2Dot" class="h-6 w-6 rounded-full bg-slate-200 text-slate-600 grid place-content-center">2</span>
            <span class="hidden sm:inline">模型选择</span>
          </li>
        </ol>
      </div>
    </div>
    <div class="h-px w-full bg-line"></div>
  </header>

  <!-- ========== 页面容器 ========== -->
  <main class="mx-auto max-w-6xl px-6 py-8">
    <!-- ===================== 第 1 步：关键词 + 生成问题 ===================== -->
    <section id="step1" class="space-y-6">
      <!-- 引导卡片 -->
      <div class="rounded-2xl border border-line bg-white shadow-card">
        <div class="grid grid-cols-1 lg:grid-cols-3">
          <!-- 左侧：输入与按钮 -->
          <div class="p-6 lg:col-span-2">
            <h2 class="text-lg font-semibold">请输入你想了解的核心关键词</h2>
            <p class="mt-1 text-sm text-slate-500">例如：<span class="font-medium">生发洗发水、户外露营帐篷、AI 写作工具</span></p>

            <!-- 输入组 -->
            <div class="mt-4 flex flex-col sm:flex-row gap-3">
              <div class="relative flex-1">
                <input id="keywordInput" type="text" placeholder="请输入你想了解的核心关键词（如 生发洗发水）"
                  class="w-full rounded-xl border border-line bg-white px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand" />
                <div class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-slate-400">⌘K</div>
              </div>
              <button id="genBtn"
                class="rounded-xl bg-brand px-5 py-3 text-sm font-medium text-white hover:bg-brand/90 active:scale-[.99]">
                生成问题
              </button>
            </div>

            <p class="mt-3 text-xs text-slate-500">我们将为你模拟真实用户在 AI 中搜索的 <b>20 种方式</b>，用于投放/SEO/内容洞察。</p>
          </div>

          <!-- 右侧：辅助信息 -->
          <div class="border-t lg:border-t-0 lg:border-l border-line p-6 bg-subtle/50 rounded-b-2xl lg:rounded-bl-none lg:rounded-r-2xl">
            <div class="text-sm font-medium">使用建议</div>
            <ul class="mt-2 space-y-2 text-sm text-slate-600 list-disc list-inside">
              <li>关键词尽量 <b>具体</b>（如「防脱生发洗发水」）。</li>
              <li>适用于 ChatGPT、Google AIO、Perplexity 等模型的提问模拟。</li>
              <li>可多次生成，选择你最关心的 5 个问题进入下一步。</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 结果面板：问题列表 -->
      <div id="questionPanel" class="hidden rounded-2xl border border-line bg-white shadow-card">
        <div class="flex items-center justify-between gap-4 border-b border-line px-6 py-4">
          <div>
            <div class="font-semibold">已为你生成 20 个问题</div>
            <div class="text-sm text-slate-500">请从中选择最多 <b>5</b> 个（已选 <span id="selCount">0</span>/5）</div>
          </div>
          <div class="flex items-center gap-2">
            <button id="regenBtn" class="rounded-lg border border-line px-3 py-2 text-sm hover:bg-slate-50">重新生成</button>
            <button id="clearBtn" class="rounded-lg border border-line px-3 py-2 text-sm hover:bg-slate-50">清空选择</button>
          </div>
        </div>

        <!-- 列表网格 -->
        <div id="questionGrid" class="grid grid-cols-1 md:grid-cols-2 gap-3 p-6">
          <!-- JS 动态插入 20 条 -->
        </div>

        <!-- 固定底部操作区 -->
        <div class="flex items-center justify-between gap-4 border-t border-line bg-slate-50/60 px-6 py-4 rounded-b-2xl">
          <div id="tip" class="text-sm text-slate-500" aria-live="polite">最多选择 5 个问题。</div>
          <button id="nextBtn" disabled
            class="rounded-xl bg-brand/40 px-5 py-3 text-sm font-medium text-white disabled:cursor-not-allowed">
            下一步
          </button>
        </div>
      </div>
    </section>

    <!-- ===================== 第 2 步：模型选择 ===================== -->
    <section id="step2" class="hidden space-y-6">
      <!-- 顶部返回 + 摘要 -->
      <div class="rounded-2xl border border-line bg-white shadow-card">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 p-6">
          <div class="flex items-center gap-3">
            <button id="backBtn" class="rounded-lg border border-line px-3 py-2 text-sm hover:bg-slate-50">← 返回问题选择</button>
            <div>
              <div class="font-semibold">模型选择</div>
              <div class="text-sm text-slate-500">选择将要查询的 AI 平台 / 模型</div>
            </div>
          </div>
          <div class="text-sm">
            <span class="text-slate-500">已选问题：</span>
            <span id="selectedChips" class="inline-flex flex-wrap gap-2 align-middle"></span>
          </div>
        </div>
        <div class="h-px bg-line"></div>

        <!-- 模型网格 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-6">
          <!-- <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" checked data-model="ChatGPT">
            <div>
              <div class="font-medium">ChatGPT</div>
              <div class="text-xs text-slate-500">适合综合问答与品牌可见度验证</div>
            </div>
          </label>

          <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" checked data-model="Google AIO">
            <div>
              <div class="font-medium">Google AIO</div>
              <div class="text-xs text-slate-500">具备 AI Overview，关注引用与外链</div>
            </div>
          </label>

          <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" checked data-model="Perplexity">
            <div>
              <div class="font-medium">Perplexity</div>
              <div class="text-xs text-slate-500">善于聚合检索，引用较完整</div>
            </div>
          </label> -->

          <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" data-model="DeepSeek">
            <div>
              <div class="font-medium">DeepSeek</div>
              <div class="text-xs text-slate-500">中文技术问题表现优秀</div>
            </div>
          </label>

          <!-- <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" data-model="Kimi">
            <div>
              <div class="font-medium">Kimi</div>
              <div class="text-xs text-slate-500">长文档与中文内容友好</div>
            </div>
          </label>

          <label class="group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer">
            <input type="checkbox" class="mt-1 h-4 w-4 accent-brand" data-model="豆包">
            <div>
              <div class="font-medium">豆包</div>
              <div class="text-xs text-slate-500">国内生态广，覆盖常见问题</div>
            </div>
          </label> -->
        </div>

        <div class="flex items-center justify-between gap-4 border-t border-line bg-slate-50/60 px-6 py-4 rounded-b-2xl">
          <div id="modelTip" class="text-sm text-slate-500" aria-live="polite">建议至少选择 1 个模型。</div>
          <button id="startBtn"
            class="rounded-xl bg-brand px-5 py-3 text-sm font-medium text-white hover:bg-brand/90 active:scale-[.99]">
            开始执行（示例）
          </button>
        </div>
      </div>
    </section>

    <!-- ===================== 第 3 步：结果展示 ===================== -->
    <section id="step3" class="hidden space-y-6">
      <!-- ===== 顶部摘要区 ===== -->
      <header class="bg-white sticky top-0 z-20 border-b border-line/80">
        <div class="mx-auto max-w-6xl px-6">
          <div class="flex flex-wrap items-center justify-between gap-4 py-4">
            <div class="flex items-center gap-3">
              <div class="h-10 w-10 rounded-xl bg-brand/10 text-brand grid place-content-center text-lg font-semibold">G</div>
              <div>
                <div class="font-semibold leading-5">GEO Studio · AI 提问结果</div>
                <div class="text-xs text-slate-500 leading-4">审阅截图 + 文本 + 引用信源（可导出）</div>
              </div>
            </div>
            <!-- 导出按钮组 -->
            <div class="no-print flex flex-wrap items-center gap-2">
              <button class="rounded-lg border border-line bg-white px-3 py-2 text-sm hover:bg-slate-50" onclick="expandAll(true)">展开全部</button>
              <button class="rounded-lg border border-line bg-white px-3 py-2 text-sm hover:bg-slate-50" onclick="expandAll(false)">收起全部</button>
              <span class="mx-1 h-5 w-px bg-line"></span>
              <button class="rounded-lg bg-brand text-white px-3 py-2 text-sm hover:bg-brand/90" onclick="exportPDF()">导出 PDF</button>
              <button class="rounded-lg border border-line bg-white px-3 py-2 text-sm hover:bg-slate-50" onclick="exportWord()">导出 Word</button>
              <button class="rounded-lg border border-line bg-white px-3 py-2 text-sm hover:bg-slate-50" onclick="exportCSV()">导出 Excel(CSV)</button>
            </div>
          </div>
        </div>
      </header>

      <!-- ===== 顶部信息条：关键词 / 模型 / 时间戳 ===== -->
      <section id="summary" class="mx-auto max-w-6xl px-6 py-6">
        <div class="page rounded-2xl border border-line bg-white shadow-card p-6">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <!-- 关键词 -->
            <div class="flex items-start gap-3">
              <div class="h-10 w-10 rounded-xl bg-brand/10 text-brand grid place-content-center text-lg">🔎</div>
              <div>
                <div class="text-sm text-slate-500">当前关键词</div>
                <div class="mt-1 font-medium" id="sumKeyword">生发洗发水</div>
              </div>
            </div>
            <!-- 模型 -->
            <div class="flex items-start gap-3">
              <div class="h-10 w-10 rounded-xl bg-brand/10 text-brand grid place-content-center text-lg">🤖</div>
              <div class="min-w-0">
                <div class="text-sm text-slate-500">所使用的 AI 模型</div>
                <div class="mt-2 flex flex-wrap gap-2" id="sumModels">
                  <!-- 模型将通过JavaScript动态添加 -->
                </div>
              </div>
            </div>
            <!-- 时间戳 -->
            <div class="flex items-start gap-3">
              <div class="h-10 w-10 rounded-xl bg-brand/10 text-brand grid place-content-center text-lg">⏱️</div>
              <div>
                <div class="text-sm text-slate-500">时间信息</div>
                <div class="mt-1 text-sm">
                  <div>提问时间：<span id="askAt">2025-07-30 10:03:12</span></div>
                  <div>回答完成：<span id="doneAt">2025-07-30 10:04:28</span></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- ===== 问题列表（Accordion） ===== -->
      <main id="printArea" class="mx-auto max-w-6xl px-6 pb-16 space-y-4">
        <!-- 问题将通过JavaScript动态添加 -->
        <div id="questionsContainer"></div>
      </main>
    </section>
  </main>

  <!-- ========== 简易 Toast ========== -->
  <div id="toast" class="fixed left-1/2 top-20 -translate-x-1/2 hidden">
    <div class="rounded-full bg-black/80 text-white text-xs px-3 py-2 shadow-card">已完成</div>
  </div>

  <!-- ========== 交互脚本 ========== -->
  <script>
    const state = {
      keyword: '',
      questions: [],
      selected: new Set(),
    };

    const el = (sel) => document.querySelector(sel);
    const els = (sel) => Array.from(document.querySelectorAll(sel));

    const keywordInput = el('#keywordInput');
    const genBtn = el('#genBtn');
    const regenBtn = el('#regenBtn');
    const clearBtn = el('#clearBtn');
    const questionPanel = el('#questionPanel');
    const questionGrid = el('#questionGrid');
    const selCount = el('#selCount');
    const tip = el('#tip');
    const nextBtn = el('#nextBtn');
    const step1 = el('#step1');
    const step2 = el('#step2');
    const backBtn = el('#backBtn');
    const step2Dot = el('#step2Dot');
    const selectedChips = el('#selectedChips');
    const startBtn = el('#startBtn');
    const step3 = el('#step3');
    const resultsContainer = el('#questionsContainer');
    const backToModelsBtn = el('#backBtn');

    // 模板库：将关键词插入不同的真实用户提问方式
    const templates = [
      '买{kw}要避坑哪些点？有没有对比建议？',
      '{kw}哪个牌子性价比高？百元内有推荐吗？',
      '{kw}真实有效吗？有没有用户复购/评价数据？',
      '{kw}和同价位竞品相比核心差异是啥？',
      '{kw}适合什么人群？敏感肌/油皮能用吗？',
      '{kw}成分表怎么看？有没有功效级证据？',
      '{kw}什么时候用效果最好？早上还是晚上？',
      '关于{kw}，有哪些常见误区或营销话术？',
      '{kw}有什么副作用/不良反应需要注意？',
      '{kw}适合长期使用吗？需要换着用吗？',
      '{kw}推荐的使用步骤和搭配是怎样的？',
      '{kw}线下和线上哪里买更划算？有活动吗？',
      '{kw}真实口碑如何？有没有达人/医生建议？',
      '{kw}海外用户怎么评价？和国内有差异吗？',
      '{kw}的核心参数/规格应该怎么选？',
      '{kw}售后/退换货保障怎么样？官方渠道是？',
      '{kw}是否环保/无硅油/无酒精等？',
      '{kw}价格区间怎么选？入门款/进阶款区别？',
      '{kw}适合送礼吗？不同场景怎么选？',
      '{kw}7 天/30 天内能看到什么变化？',
      '第一次买{kw}应该从哪一款开始？',
      '{kw}有哪些黑名单或不建议购买的型号？',
      '{kw}适用于哪些场景？出差/健身/旅行？',
      '如果{kw}无效，有哪些替代方案？',
      '关于{kw}的最新测评/横评有吗？',
      '{kw}有哪些隐藏用法或效率技巧？',
      '我预算 300 元，{kw}怎么搭配最划算？',
      '{kw}是否需要配合饮食/运动/医美？',
      '购买{kw}前需要做哪些功课？',
      '新手买{kw}容易踩的坑有哪些？'
    ];

    // 生成 20 个不重复问题
    function generateQuestions(kw) {
      const pool = [...templates];
      const result = [];
      while (result.length < 20 && pool.length) {
        const idx = Math.floor(Math.random() * pool.length);
        const t = pool.splice(idx, 1)[0];
        result.push(t.replaceAll('{kw}', kw));
      }
      return result;
    }

    // 调用后端接口获取问题列表
    async function fetchQuestionsFromBackend(kw) {
      try {
        const response = await fetch('http://localhost:5001/api/generate-questions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ keyword: kw })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data.questions || [];
      } catch (error) {
        console.error('获取问题列表失败:', error);
        // 出错时回退到本地生成
        return generateQuestions(kw);
      }
    }

    function renderQuestions() {
      questionGrid.innerHTML = '';
      state.questions.forEach((q, i) => {
        const id = 'q_' + i;
        const isChecked = state.selected.has(q);
        const disabled = !isChecked && state.selected.size >= 5;
        // 每个问题卡片（checkbox + 文本）
        const item = document.createElement('label');
        item.className =
          'group flex items-start gap-3 rounded-xl border border-line bg-white px-4 py-3 hover:shadow-card cursor-pointer';
        item.innerHTML = `
          <input id="${id}" type="checkbox" class="mt-1 h-4 w-4 accent-brand"
                 ${isChecked ? 'checked' : ''} ${disabled ? 'disabled' : ''}>
          <span class="text-sm leading-6">${q}</span>
        `;
        item.querySelector('input').addEventListener('change', (e) => {
          if (e.target.checked) {
            if (state.selected.size >= 5) {
              e.target.checked = false;
              showTip('最多选择 5 个问题', true);
              return;
            }
            state.selected.add(q);
          } else {
            state.selected.delete(q);
          }
          updateSelectionUI();
        });
        questionGrid.appendChild(item);
      });
      updateSelectionUI();
    }

    function updateSelectionUI() {
      // 数量与按钮状态
      selCount.textContent = state.selected.size;
      nextBtn.disabled = state.selected.size !== 5;
      nextBtn.classList.toggle('bg-brand/40', state.selected.size !== 5);
      nextBtn.classList.toggle('bg-brand', state.selected.size === 5);
      nextBtn.classList.toggle('hover:bg-brand/90', state.selected.size === 5);

      // 未满 5 个时，允许继续勾选；满 5 后禁用其他未选项
      const inputs = els('#questionGrid input[type="checkbox"]');
      const full = state.selected.size >= 5;
      inputs.forEach((c) => {
        if (!c.checked) c.disabled = full;
      });

      // 提示文案
      if (state.selected.size < 5) {
        showTip('请选择最多 5 个问题；选满 5 个后可进入下一步。', false);
      } else {
        showTip('已选 5/5，可以进入下一步。', false);
      }
    }

    function showTip(msg, danger=false) {
      tip.textContent = msg;
      tip.className = `text-sm ${danger ? 'text-rose-600' : 'text-slate-500'}`;
    }

    function toast(msg) {
      const t = document.getElementById('toast');
      t.querySelector('div').textContent = msg;
      t.classList.remove('hidden');
      clearTimeout(t._timer);
      t._timer = setTimeout(()=> t.classList.add('hidden'), 1600);
    }

    // 点击【生成问题】
    genBtn.addEventListener('click', async () => {
      const kw = keywordInput.value.trim();
      if (!kw) { toast('请先输入核心关键词'); return; }
      state.keyword = kw;
      state.selected.clear();

      // Loading skeleton（简易模拟）
      questionPanel.classList.remove('hidden');
      questionGrid.innerHTML =
        '<div class="col-span-full grid grid-cols-1 md:grid-cols-2 gap-3">' +
        Array.from({length: 6}).map(() =>
          '<div class="rounded-xl border border-line p-4 animate-pulse bg-subtle"></div>'
        ).join('') + '</div>';

      // 调用后端接口获取问题
      state.questions = await fetchQuestionsFromBackend(kw);
      renderQuestions();
    });

    // 重新生成
    regenBtn.addEventListener('click', () => {
      if (!state.keyword) { toast('请先输入关键词并生成'); return; }
      state.selected.clear();
      state.questions = generateQuestions(state.keyword);
      renderQuestions();
    });

    // 清空选择
    clearBtn.addEventListener('click', () => {
      state.selected.clear();
      renderQuestions();
    });

    // 下一步：进入模型选择
    nextBtn.addEventListener('click', () => {
      if (state.selected.size !== 5) { toast('请选择 5 个问题'); return; }
      step1.classList.add('hidden');
      step2.classList.remove('hidden');
      step2Dot.classList.remove('bg-slate-200', 'text-slate-600');
      step2Dot.classList.add('bg-brand', 'text-white');
      // 展示所选问题 Chips
      selectedChips.innerHTML = '';
      [...state.selected].forEach(q => {
        const chip = document.createElement('span');
        chip.className = 'rounded-full bg-subtle px-3 py-1 text-xs text-slate-700 border border-line';
        chip.textContent = q.length > 32 ? q.slice(0, 32) + '…' : q;
        selectedChips.appendChild(chip);
      });
      window.scrollTo({top: 0, behavior: 'smooth'});
    });

    // 返回第 1 步
    backBtn.addEventListener('click', () => {
      step2.classList.add('hidden');
      step1.classList.remove('hidden');
      step2Dot.classList.remove('bg-brand', 'text-white');
      step2Dot.classList.add('bg-slate-200', 'text-slate-600');
      window.scrollTo({top: 0, behavior: 'smooth'});
    });

    // 开始执行（示例）
    startBtn.addEventListener('click', async () => {
      const models = els('#step2 input[type="checkbox"]:checked').map(i => i.dataset.model);
      if (models.length === 0) { toast('请至少选择 1 个模型'); return; }

      // 隐藏第二步，显示第三步
      step2.classList.add('hidden');
      step3.classList.remove('hidden');

      // 显示加载状态
      resultsContainer.innerHTML = '<div class="text-center py-10"><div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-brand"></div><p class="mt-2">正在获取答案...</p></div>';

      // 调用后端API获取答案
      try {
        const response = await fetch('http://localhost:5001/api/answer-questions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            keyword: state.keyword,
            questions: [...state.selected]
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.info('获取问题答案成功:', data);

        // 渲染结果到当前页面
        renderResults(data);
      } catch (error) {
        console.error('获取答案失败:', error);
        resultsContainer.innerHTML = `<div class="text-center py-10 text-red-500"><p>获取答案失败: ${error.message}</p><button id="retryBtn" class="mt-4 rounded-lg bg-brand px-4 py-2 text-white">重试</button></div>`;
        document.getElementById('retryBtn').addEventListener('click', () => {
          startBtn.click();
        });
      }

      window.scrollTo({top: 0, behavior: 'smooth'});
    });

    // 渲染结果（按照result.html的结构）
  // 渲染结果（按照result.html的结构）
function renderResults(data) {
  if (!data) return;


  console.info('初始渲染结果:', data);

  // 配置 marked 解析器
  marked.setOptions({
    breaks: true,
    gfm: true,
    highlight: function(code, lang) {
      return code;
    }
  });

  // 更新摘要信息
  document.getElementById('sumKeyword').textContent = data.keyword || state.keyword || '未指定';

  // 更新模型信息
  const modelsContainer = document.getElementById('sumModels');
  const models = els('#step2 input[type="checkbox"]:checked').map(i => i.dataset.model);
  modelsContainer.innerHTML = models.map(model =>
    `<span class="rounded-full bg-soft border border-line px-3 py-1 text-xs">${model}</span>`
  ).join('');

  // 更新时间信息
  const now = new Date();
  document.getElementById('askAt').textContent = now.toLocaleString('zh-CN');
  document.getElementById('doneAt').textContent = new Date(now.getTime() + 60000).toLocaleString('zh-CN');

  // 渲染问题和答案
  const questionsContainer = document.getElementById('questionsContainer');
  questionsContainer.innerHTML = '';

  // 获取问题列表和结果
  const questions = [...state.selected];

  // 为每个问题创建详细信息面板
  questions.forEach((question, index) => {
    // 获取结构化结果
    const resultData = data.results[question] || {
      title: question,
      content: '暂无回答',
      citations: []
    };

    console.info('resultData解析结果:', resultData);

    // 解析 Markdown 内容
    const parsedContent = marked.parse(resultData.content || '暂无回答');

    console.info('markdwon content解析结果:', parsedContent);

    // 创建问题面板
    const questionPanel = document.createElement('details');
    questionPanel.className = 'page rounded-2xl border border-line bg-white shadow-card overflow-hidden';
    if (index === 0) {
      questionPanel.setAttribute('open', '');
    }

    questionPanel.innerHTML = `
      <summary class="cursor-pointer list-none">
        <div class="flex items-start justify-between gap-4 px-5 py-4">
          <div class="flex items-start gap-3">
            <div class="caret text-brand"></div>
            <div>
              <div class="text-sm text-slate-500">问题 ${index + 1}</div>
              <h3 class="font-semibold leading-6">${question}</h3>
            </div>
          </div>
          <div class="hidden md:flex items-center gap-2 text-xs text-slate-500">
            <span class="rounded-full bg-soft border border-line px-2 py-1">模型：${models.length}</span>
            <span class="rounded-full bg-soft border border-line px-2 py-1">引用：${resultData.citations ? resultData.citations.length : 0}</span>
          </div>
        </div>
      </summary>

      <div class="border-t border-line grid grid-cols-1 xl:grid-cols-3">
        <!-- 左侧：回答文本（多模型） -->
        <div class="xl:col-span-2 p-5 space-y-4">
          ${models.map(model => `
            <article class="rounded-xl border border-line p-4">
              <header class="flex items-center justify-between">
                <div class="font-medium">${model}</div>
                <div class="text-xs text-slate-500">${new Date().toLocaleTimeString('zh-CN')}</div>
              </header>
              <div class="mt-2 text-sm leading-6 prose prose-sm max-w-none">
                ${parsedContent}
              </div>
            </article>
          `).join('')}
        </div>

        <!-- 右侧：长截图 + 引用信源 -->
        <aside class="border-t xl:border-t-0 xl:border-l border-line p-5 space-y-4">
          <!-- 截图区（JPG/PNG） -->
          <figure class="rounded-xl border border-line overflow-hidden">
            <img src="https://via.placeholder.com/1200x800.png?text=Answer+Screenshot" alt="回答长截图占位" />
            <figcaption class="p-2 text-xs text-slate-500">回答长截图（示例）</figcaption>
          </figure>

          <!-- 引用信源（高亮显示 + 可导出） -->
          <div>
            <div class="font-medium mb-2">引用与来源</div>
            <ul class="space-y-2 text-sm">
              ${resultData.citations && resultData.citations.length > 0
                ? resultData.citations.map((citation, i) => `
                  <li class="citation rounded-lg border border-brand/30 bg-brand/5 px-3 py-2"
                      data-question="${question}"
                      data-model="${models.join(', ')}"
                      data-title="${citation.title || '引用链接 ' + (i+1)}"
                      data-url="${citation.url}">
                    <div class="flex items-center justify-between gap-3">
                      <a href="${citation.url}" class="text-brand hover:underline" target="_blank" rel="noreferrer">
                        ${citation.title || '引用链接 ' + (i+1)}
                      </a>
                      <span class="text-xs text-slate-500">${models[0]}</span>
                    </div>
                    <div class="text-xs text-slate-500 truncate">${citation.url}</div>
                  </li>
                `).join('')
                : `<li class="text-slate-500 text-sm">暂无引用链接</li>`
              }
            </ul>

            <!-- 单问题导出（可选） -->
            <div class="no-print mt-3 flex items-center gap-2">
              <button class="rounded-lg border border-line bg-white px-3 py-1.5 text-xs hover:bg-slate-50" onclick="exportWord('#q${index}')">导出此问题 Word</button>
              <button class="rounded-lg border border-line bg-white px-3 py-1.5 text-xs hover:bg-slate-50" onclick="exportCSV('#q${index}')">导出此问题 CSV</button>
            </div>
          </div>
        </aside>
      </div>
      <!-- 用于单题导出的定位锚点 -->
      <div id="q${index}"></div>
    `;

    questionsContainer.appendChild(questionPanel);
  });
}

    // --- 展开 / 收起全部 ---
    function expandAll(open=true){
      document.querySelectorAll('main details').forEach(d => d.open = !!open);
    }

    // --- 导出为 PDF（打印） ---
    function exportPDF(){
      expandAll(true);                     // 打印前展开
      setTimeout(()=>window.print(), 50);  // 触发打印（用户可选"另存为 PDF"）
    }

    // --- 导出 Word（将指定区域的 HTML 包裹为 .doc） ---
    function exportWord(scopeSelector){
      const scope = scopeSelector ? document.querySelector(scopeSelector).closest('details') : document.getElementById('printArea');
      const clone = scope.cloneNode(true);

      // Word 里不需要按钮
      clone.querySelectorAll('.no-print').forEach(n => n.remove());

      const html =
`<!DOCTYPE html><html><head><meta charset="utf-8">
<style>
body{font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif}
img{max-width:100%}
summary{font-weight:600}
</style>
</head><body>${document.getElementById('summary').outerHTML}${clone.outerHTML}</body></html>`;

      const blob = new Blob(['\ufeff', html], {type: 'application/msword'});
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = scopeSelector ? 'question.doc' : 'ai-results.doc';
      a.click();
      URL.revokeObjectURL(url);
      toast('已导出 Word');
    }

    // --- 导出 CSV（Excel 可打开）：汇总 citation 列表 ---
    function exportCSV(scopeSelector){
      const root = scopeSelector
        ? document.querySelector(scopeSelector).closest('details')
        : document.getElementById('printArea');

      const rows = [['问题','模型','标题','URL']]; // 表头
      root.querySelectorAll('.citation').forEach(c => {
        rows.push([
          (c.dataset.question || '').replace(/\n/g,' ').trim(),
          c.dataset.model || '',
          c.dataset.title || '',
          c.dataset.url || ''
        ]);
      });

      const csv = rows.map(r => r.map(cell => `"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
      const blob = new Blob(['\ufeff', csv], {type:'text/csv;charset=utf-8;'});
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = scopeSelector ? 'question.csv' : 'citations.csv';
      a.click();
      URL.revokeObjectURL(url);
      toast('已导出 CSV');
    }

    // --- 小提示 ---
    function toast(msg){
      const t = document.getElementById('toast');
      t.querySelector('div').textContent = msg;
      t.classList.remove('hidden');
      clearTimeout(t._timer);
      t._timer = setTimeout(()=> t.classList.add('hidden'), 1400);
    }
  </script>
</body>
</html>
